<template>
	<view class="swap">
		<u-navbar back-icon-color="#FFFFFF" title-color="#FFFFFF" :border-bottom="false"
			:background="{background:'linear-gradient(to right, #0A0A25 30%,#220B4E 60%, #083842 80%)'}"
			title="KRSwap"></u-navbar>

		<view class="he4"></view>

		<view class="info">
			<view class="mg-b-40 f32">Swap</view>
			<view class="to">
				<view class="fsb">
					<view class="zindex exchange-btn">
						<image :src="toList.pic" style="width: 40rpx;height: 40rpx;"></image>
						<view class="mg-l-10 mg-r-10">{{toList.name}}</view>
					</view>
					<view class="">{{i18n.balance}}：{{toList.money}}</view>
				</view>
				<view class="zindex fsb mg-t-50">
					<input type="number" maxlength="16" style="width: 100% !important;" placeholder="0.00" v-model="to"
						@input="oninput">
				</view>
			</view>
			<view class="exchange">
				<image src="@/static/add/swap-duih.png" style="width: 89.6rpx;height: 89.6rpx;" @click="interchange">
				</image>
			</view>
			<view class="from">
				<view class="fsb">
					<view class="zindex exchange-btn">
						<image :src="fromList.pic" style="width: 40rpx;height: 40rpx;"></image>
						<view class="mg-l-10 mg-r-10">{{fromList.name}}</view>
					</view>
					<view class="zindex">{{i18n.balance}}：{{fromList.money}}</view>
				</view>
				<view class="zindex fsb mg-t-50">≈{{from}}</view>
			</view>
			<!-- <view class="fsb mg-l-10 mg-r-10">
				<view class=" ">{{i18n.Slippage}}</view>
				<view class=" ">15%</view>
			</view> -->
			<view class="btn" @click="exchange">{{i18n.exchange}}</view>
		</view>

		<view class="text-a mg-t-150">
			<image src="@/static/add/home-logo.png" mode="widthFix" style="width: 416rpx;"></image>
		</view>

	</view>
</template>

<script>
	var that
	import {
		_updataTabBar,
		pageto,
		fetch,
		showToast
	} from "../../common/js/sysfun.js"
	import Web3 from "web3";
	import abi from "../../common/abi/BSC.js";
	import {
		mapGetters,
		mapMutations
	} from 'vuex'
	import {
		BigNumber
	} from "ethers";

	let toList = {
		id: 0,
		name: 'USDT',
		money: '0.00',
		pic: "/static/add/USDT.png",
	}

	let fromList = {
		id: 1,
		name: 'KR',
		money: '0.00',
		pic: "/static/add/KP.png",
	}

	export default {
		data() {
			return {
				show: false,
				type: false,
				status: "",
				toList,
				fromList,
				toListID: false,
				fromListID: false,
				to: '',
				from: 0,
				address: ''
			}
		},
		onLoad() {

		},
		onShow() {
			this.address = this.getLoginInfo.address
			this.getData()
			this.getBlance()
		},
		computed: {
			i18n() {
				return this.$t('message');
			},
			...mapGetters([
				'getLoginInfo',
				'getUsdt',
				'getKr',
				'getBonus',
				'getIsBlance'
			])
		},
		methods: {
			...mapMutations([
				'setIsBlance'
			]),

			// 获取数据
			async getData() {
				that = this
				if (window.ethereum) {
					let ethereum = window.ethereum
					let web3 = new Web3(ethereum);
					let uContract = new web3.eth.Contract(abi, that.getUsdt)
					let kContract = new web3.eth.Contract(abi, that.getKr)
					let uBalance = await uContract.methods.balanceOf(that.address).call()
					let kBalance = await kContract.methods.balanceOf(that.address).call()
					// let Balance = await uContract.methods.getUSDTLimit(that.address).call()
					// console.log(Balance)
					if (that.toList.name == "USDT") {
						that.toList.money = that.getBalance(uBalance / Math.pow(10, 18))
						that.fromList.money = that.getBalance(kBalance / Math.pow(10, 18))
					} else {
						that.toList.money = that.getBalance(kBalance / Math.pow(10, 18))
						that.fromList.money = that.getBalance(uBalance / Math.pow(10, 18))
					}
				}
			},

			getBlance() {
				that.$getAjax('member/usdtvkr', '', function(res) {
					let data = {
						money: res.data,
						is: true,
						lv: that.getLoginInfo.name
					}
					that.setIsBlance(data)
				})
			},

			getBalance(val) {
				return val.toFixed(2)
			},

			init(type = true) {
				this.to = ''
				this.from = 0
				if (type) {
					this.getData()
				}
			},

			interchange() {
				this.init(false)
				const data = this.toList
				this.toList = this.fromList
				this.fromList = data
			},

			oninput(e) {
				this.$u.debounce(this.getTokens, 300)
			},

			initialize(val = false) {
				if (val) {
					showToast(val)
				}
				setTimeout(() => {
					uni.hideLoading()
					this.init()
				}, 1500)
			},

			setlv(val, tyep = false) {
				let isData = this.getIsBlance
				isData.is = val
				if (tyep) {
					isData.money = Number(isData.money) - Number(tyep)
				}
				this.setIsBlance(isData)
			},

			async getTokens() {
				that = this
				if (that.to <= 0) return
				that.toList.id == 0 ? that.type = true : that.type = false
				if (window.ethereum) {
					let ethereum = window.ethereum
					let web3 = new Web3(ethereum);
					let ethContract = new web3.eth.Contract(abi, that.getKr)
					const amountIn = web3.utils.toWei(that.to + '', "ether")
					if (that.type) {
						ethContract.methods.getAmountkfOut(amountIn)
							.call()
							.then(result => {
								let u = that.getBalance(result / Math.pow(10, 18))
								that.from = Number(u) * 0.30
							})
							.catch(error => {
								showToast(error.message)
								that.to = ''
							})
					} else {
						ethContract.methods.getAmountUsdtOut(amountIn)
							.call()
							.then(result => {
								let k = that.getBalance(result / Math.pow(10, 18))
								that.from = Number(k) * 0.85
							})
							.catch(error => {
								showToast(error.message)
								that.to = ''
							})
					}
				}
			},



			async exchange() {
				that = this
				if (!that.to) return
				if (that.toList.name == "USDT" && (that.to) > Number(that.getIsBlance.money)) {
					return showToast(that.i18n.Insufficientamount)
				}
				if (Number(that.to) > Number(that.toList.money)) return showToast(that.i18n.InBalance)
				if (window.ethereum) {
					let ethereum = window.ethereum
					let web3 = new Web3(ethereum);
					let ethContract = new web3.eth.Contract(abi, that.getUsdt)
					let krContract = new web3.eth.Contract(abi, that.getKr)
					const amount = web3.utils.toWei(that.to + '', "ether")
					const tokensToSell = amount
					const amountU = amount
					uni.showLoading({
						title: that.i18n.Authorizing,
						mask: true
					})
					web3.eth.getGasPrice().then((currentGasPrice) => {
							let gasPriceInWei = Math.floor(currentGasPrice * 1.5)
							if (that.type) {
								ethContract.methods.allowance(that.address, that.getKr).call()
									.then(allowedAmount => {
										if (Number(allowedAmount) < amount) {
											return ethContract.methods.approve(that.getKr, amount + '').send({
												from: that.address,
												gasPrice: gasPriceInWei.toString() // 设置交易的Gas价格
											})
										} else {
											return Promise.resolve()
										}
									})
									.catch(error => {
										that.initialize(error.message)
										return Promise.reject()
									})
									.then(() => {
										that.setlv(false)
										return krContract.methods.buyKr(amountU + '')
											.send({
												from: that.address,
												gasPrice: gasPriceInWei.toString() // 设置交易的Gas价格
											})
									})
									.then(result => {
										that.setlv(true, that.to)
										that.initialize(that.i18n.Paymentsuccessful)
									})
									.catch(error => {
										that.setlv(true)
										that.initialize(error.message)
									})
							} else {
								krContract.methods.sellKr(tokensToSell + '')
									.send({
										from: that.address,
										gasPrice: gasPriceInWei.toString() // 设置交易的Gas价格
									})
									.then(result => {
										that.initialize(that.i18n.Paymentsuccessful)
									})
									.catch(error => {
										that.initialize(error.message)
									})
							}
					});
			}
		},
		pageto(url, pp) {
			pageto(url, pp);
		},
	},
	onReachBottom() {

	},
	}
</script>

<style lang="scss" scoped>
	.swap {
		color: #FFFFFF;
		height: 100vh;
		background-image: url(@/static/add/invite-bg.png);
		background-repeat: no-repeat;
		background-size: 100% 100%;

		.info {
			margin: 0 20rpx;
			padding: 40rpx 40rpx 70rpx;
			border-radius: 40rpx;
			background-color: rgba(81, 95, 140, .5);
			box-shadow: inset -4rpx -4rpx 6rpx 2rpx rgba(81, 95, 140, .5);

			.exchange {
				text-align: center;
				margin-top: -30rpx;
			}

			uni-image {
				z-index: 2;
			}

			.to,
			.from {
				position: relative;
				overflow: hidden;
				padding: 40rpx;
				border-radius: 40rpx;
				background-color: #010A38;
			}

			.zindex {
				position: relative;
				z-index: 2;
			}

			.exchange-btn {
				display: flex;
				align-items: center;
				width: fit-content;
				padding: 14rpx 20rpx;
				border-radius: 30rpx;
				background-color: rgba(107, 78, 115, .4);
			}

			.to {}

			.from {
				transform: translateY(-30rpx);
			}

			.to::before {
				content: "";
				position: absolute;
				top: 0;
				left: 0;
				width: 110rpx;
				height: 100%;
				background: linear-gradient(to top right, #B22CD8 0%, #2E1261 30%, #010A38 100%);
			}

			.to::after {
				content: "";
				position: absolute;
				left: 8rpx;
				bottom: 8rpx;
				width: 102rpx;
				height: 100%;
				border-radius: 0 0 0 30rpx;
				background: linear-gradient(to top right, #4E3278 0%, #2E1261 10%, #010A38 60%);
				z-index: 1;
			}

			.from::before {
				content: "";
				position: absolute;
				top: 0;
				right: 0;
				width: 110rpx;
				height: 100%;
				background: linear-gradient(to top left, #11E8CE 0%, #032449 30%, #010A38 54%);
			}

			.from::after {
				content: "";
				position: absolute;
				right: 8rpx;
				bottom: 8rpx;
				width: 102rpx;
				height: 100%;
				border-radius: 0 0 30rpx 0;
				background: linear-gradient(to top left, #053E5B 0%, #021B44 30%, #010A38 54%);
				z-index: 1;
			}
		}

		.btn {
			margin-top: 50rpx;
			padding: 30rpx;
			font-size: 32rpx;
			text-align: center;
			border-radius: 20rpx;
			background: linear-gradient(to right, #B22CD8, #24EEBE);
		}

		/deep/ .u-drawer-bottom {
			background: #2D3459;
		}

		.title {
			height: 90rpx;
			line-height: 90rpx;
			padding-left: 30rpx;
			font-weight: bold;
			border-bottom: 4rpx solid rgba(255, 255, 255, .2);
		}

		.pop-info {
			padding: 20rpx 30rpx;
		}
	}
</style>